__author__ = 'l4537'
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#coding:utf-8
import re
from san import models
from django.db.models import Q
from scriptd.tasks import Task
def Re(res,total,id = "1"):
    if id == "1":
        data = re.findall(str(res),total)
    if id == "2":
        data = re.findall(str(res),total,re.M)
    if id == "3":
        data = re.findall(str(res),total,re.S)
    return data
def Huansuan(num):
    if "g" in num:
        c = num.strip("g")
        d = float(c) * 1024
        return round(d,3)
    elif "m" in num:
        return num.strip("m")
    elif "k" in num:
        c = num.strip("k")
        d = float(c) / 1024
        return round(d,3)
    elif num == "":
        return ""
    else:
        d = float(num) / 1024 / 1024
        return round(d,4)
class Sanmessages():
    def __init__(self,data):
        self.data = data
    def Index(self):
        a = Re(r'(\d+\s+\d+\s+\d+|\d+\s+\d+)\s+(\S{6})\s+\S{2}\s+(\S{2,3})\s+(\S+)\s+FC\s+(\s|\S+\s+..:..:..:..:..:..:..:..)',self.data)
        Index ={}
        for i in a:
            port_mess = i[0].split(" ")
            while "" in port_mess:
                port_mess.remove("")
            Index[port_mess[0]] = {}
            wwn_mess = i[4].split(" ")
            while "" in wwn_mess:
                wwn_mess.remove("")
            while "\n" in wwn_mess:
                wwn_mess.remove("\n")
            if len(port_mess) == 3:
                Index[port_mess[0]]["slot"] = int(port_mess[1])
                Index[port_mess[0]]["port"] = int(port_mess[2])
                Index[port_mess[0]]["fcid"] = i[2]
                Index[port_mess[0]]["speed"] = i[3]
                if len(wwn_mess) ==2 :
                    Index[port_mess[0]]["type"] = wwn_mess[0]
                    Index[port_mess[0]]["wwn"] = wwn_mess[1]
                else:
                    Index[port_mess[0]]["type"] = ""
                    Index[port_mess[0]]["wwn"] = ""
            if len(port_mess) == 2:
                Index[port_mess[0]]["slot"] = None
                Index[port_mess[0]]["port"] = int(port_mess[1])
                Index[port_mess[0]]["fcid"] = i[2]
                Index[port_mess[0]]["speed"] = i[3]
                if len(wwn_mess) ==2 :
                    Index[port_mess[0]]["type"] = wwn_mess[0]
                    Index[port_mess[0]]["wwn"] = wwn_mess[1]
                else:
                    Index[port_mess[0]]["type"] = ""
                    Index[port_mess[0]]["wwn"] = ""
        return Index
    def Porterr(self):
        data_indx = self.Index()
        data = {}
        a = Re(r"(\d+):\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\d+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)",self.data)
        for i in data_indx:
            for ii in a:
                if i == ii[0]:
                    data[i] = {}
                    # data[i]["tx"] = ""
                    # data[i]["rx"] = ""
                    data[i]["enc_in"] = ii[3]
                    data[i]["crc_err"] = ii[4]
                    data[i]["crc_g_eof"] = ii[5]
                    data[i]["two_shrt"] = ii[6]
                    data[i]["two_long"] = ii[7]
                    data[i]["bad_eof"] = ii[8]
                    data[i]["enc_out"] = ii[9]
                    data[i]["disc_c3"] = ii[10]
                    data[i]["link_fail"] = ii[11]
                    data[i]["loss_sync"] = ii[12]
                    data[i]["loss_sig"] = ii[13]
                    data[i]["frjt"] = ii[14]
                    data[i]["fbsy"] = ii[15]
                    # data[i]["timeout_tx"] = ii[16]
                    # data[i]["timeout_rx"] = ii[17]
        return data
    def Sfpshow(self):
        rightdata = {}
        right1 = Re("Slot\s+(\d{1,2})/Port\s+(\d+).*?RX Power:\s+(\S+).*?TX Power:\s+(\S+)",self.data,"3")
        right2 = Re("Port\s+(\d+).*?RX Power:\s+(\S+).*?TX Power:\s+(\S+)",self.data,"3")
        if right2:
            for i in right2:
                rightdata[i[0]] ={}
                rightdata[i[0]]["RX_Power"] =i[1]
                rightdata[i[0]]["TX_Power"] =i[2]
        if right1:
            indexmess = self.Index()
            for i in right1:
                for k in indexmess:
                    if i[0] == indexmess[k]["slot"] and i[1] == indexmess[k]["port"]:
                        rightdata[k] ={}
                        rightdata[k]["RX_Power"] = i[2]
                        rightdata[k]["TX_Power"] = i[3]
        return rightdata
    def Hardware(self):
        pass

#单个更新
def sanportdata(id,text):
    task = Task()
    data = Sanmessages(text)
    index = data.Index()
    porterr = data.Porterr()
    sfpshow = data.Sfpshow()
    task.start(str("博科光交" + id + "-" + "开始刷新数据"))
    for i in index:
        data ={
            "index":i,
            "slot":index[i]["slot"],
            "port":index[i]["port"],
            "san_id":id,
        }
        obj = models.Sanport.objects.filter(index=i,port=index[i]["port"],san_id=id).first()
        if not obj:
            obj = models.Sanport.objects.create(**data)
        obj.speed = index[i]["speed"]
        obj.type = index[i]["type"]
        obj.fcid = index[i]["fcid"]
        obj.enc_in = porterr[i]["enc_in"]
        obj.crc_g_eof = porterr[i]["crc_g_eof"]
        obj.two_shrt = porterr[i]["two_shrt"]
        obj.enc_out = porterr[i]["enc_out"]
        obj.disc_c3 = porterr[i]["disc_c3"]
        obj.link_fail = porterr[i]["link_fail"]
        obj.loss_sync = porterr[i]["loss_sync"]
        obj.loss_sig = porterr[i]["loss_sig"]
        obj.frjt = porterr[i]["frjt"]
        obj.fbsy = porterr[i]["fbsy"]
        # obj.timeout_tx = porterr[i]["timeout_tx"]
        # obj.timeout_rx = porterr[i]["timeout_rx"]
        # obj.tx = porterr[i]["tx"]
        # obj.rx = porterr[i]["rx"]
        if i in sfpshow:
            obj.RX_Power = sfpshow[i]["RX_Power"]
            obj.TX_Power = sfpshow[i]["TX_Power"]
        else:
            obj.RX_Power = "None"
            obj.TX_Power = "None"
        obj.save()
        if index[i]["wwn"]:
            wwn = models.Wwn.objects.update_or_create(wwn = index[i]["wwn"])
            wwn[0].Sanport_wwn = obj
            wwn[0].save()
    task.end()
def sanportsum(id):
    sanport = models.Sanport.objects.filter(san_id = id)
    i = models.San.objects.get(id = id)
    if sanport:
        onlineport = 0
        availableport = 0
        nomodelport = 0
        for p in sanport:
            if p.speed == "Online":
                onlineport +=1
            elif p.speed == "No_Light":
                availableport +=1
            elif p.speed =="No_Module":
                nomodelport += 1
        otherport = int(len(sanport)) - int(availableport) - int(nomodelport)
        i.onlineport = onlineport
        i.availableport = availableport
        i.nomodelport = nomodelport
        i.otherport = otherport
        i.save()
